package com.spel.core.interceptor;

import com.spel.core.context.ContextHolder;
import com.spel.vo.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @title: LoginInterceptor
 * @Author xu-xiang
 * @Date: 2024/1/30 15:51
 * @description:
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        LoginUser loginUser = getLoginUser(authorization);
        ContextHolder.set("loginUser", loginUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextHolder.remove();
    }

    private LoginUser getLoginUser(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
            //throw new RuntimeException("请先登录");
        }

        // 模拟获取登录信息
        LoginUser loginUser = new LoginUser();
        loginUser.setAdmin(false);
        loginUser.setRoleList(Arrays.asList("CEO", "COO"));
        loginUser.setPermissionList(Arrays.asList("queryUser", "deleteUser"));
        return loginUser;
    }
}
